# -*- coding:utf-8 -*-

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from disn.utilities import *
import logging, datetime, time, qrcode, os
from django.db import IntegrityError
from disn.settings import PROJECT_PATH, BASE_DIR
from django.db.models import Count
from xpinyin import Pinyin
from disn.settings import redis_instance
from account.models import Mall
from taskqueue.tasks import fetch_book_info_by_sku

pinyin = Pinyin()

LINKSTARS_CHANNEL_ITEMS = (
    ('1915', '亲近母语官网'),
    ('1916', 'QQ'),
    ('1917', '环紫金山微博'),
    ('1918', '舜易咨询官网'),
    ('1919', '环紫金山的微信'),
    ('1920', '环紫金山的博客'),
    ('2923', '每周精选购'),
    ('3117', 'ztm.me'),
)

FROM_ITEMS = (
    ('0', '手动录入'),
    ('1', '京东'),
    ('2', '豆瓣'),
)

class Category(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True, verbose_name='分类名称')
    code = models.CharField(max_length=100, blank=True, null=True, verbose_name='分类代码')
    pinyin = models.CharField(max_length=100, blank=True, null=True, verbose_name='分类全拼')
    parent = models.ForeignKey("self", blank=True, null=True, verbose_name='上层分类')
    url = models.CharField(max_length=200, blank=True, null=True, verbose_name='分类URL')
    active = models.BooleanField(default=True, verbose_name='有效')
    order = models.IntegerField(default=-1, verbose_name='排序')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')
    remarks = models.TextField(blank=True,null=True,verbose_name='备注')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        if self.name:
            self.code = pinyin.get_initials(self.name, '')
            self.pinyin = pinyin.get_pinyin(self.name)
        return super(Category, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '图书分类'
        verbose_name_plural = '图书分类'
        ordering = ('-modify_at', '-create_at')

    def __str__(self):
        return self.name

    @staticmethod
    def get_name_by_pinyin(pinyin):
        if pinyin and len(pinyin) > 0:
            name = redis_instance.get(pinyin)
            if not name:
                try:
                    category = Category.objects.get(pinyin=pinyin)
                    name = category.name
                    redis_instance.set(name=pinyin, value=name)
                except Category.DoesNotExist as e:
                    print(e)
                except Exception as e:
                    print(e)
            return name
        else:
            return None

class Book(models.Model):
    url = models.CharField(max_length=200, blank=True, null= True, verbose_name='图书URL')
    sku = models.CharField(max_length=30, blank=True, null=True, verbose_name='图书SKU')
    name = models.CharField(max_length=200, blank=True, null=True, verbose_name='图书名称')
    name_py = models.CharField(max_length=500, blank=True, null=True, verbose_name='图书名称拼音')
    data_from = models.CharField(max_length=1, null=True, blank=True, verbose_name='数据来源', choices=FROM_ITEMS)
    price = models.CharField(max_length=50, blank=True, null=True, verbose_name='价格')
    top_category = models.ForeignKey(Category, blank=True, null=True, verbose_name='分类大类') # f:article_top_category
    sub_category = models.CharField(max_length=50, blank=True, null=True, verbose_name='分类子类')
    summary = models.TextField(blank=True, null=True, verbose_name='商品简介')
    content = models.TextField(blank=True, null=True, verbose_name='详细内容')
    mall = models.ForeignKey(Mall, blank=True, null=True, verbose_name='商城', related_name='book_mall')
    pic_url = models.CharField(max_length=300, blank=True, null=True, verbose_name='图书配图')
    author = models.CharField(max_length=50, blank=True, null=True, verbose_name='作者')
    translator = models.CharField(max_length=50, blank=True, null=True, verbose_name='译者')
    pub = models.CharField(max_length=50, blank=True, null=True, verbose_name='出版社')
    pub_date = models.CharField(max_length=20, blank=True, null=True, verbose_name='出版日期')
    url_refer = models.CharField(max_length=500, blank=True, null= True, verbose_name='商品推荐URL')
    url_refer_mb = models.CharField(max_length=500, blank=True, null= True, verbose_name='商品推荐移动URL')
    grade = models.CharField(max_length=20, blank=True, null=True, verbose_name='推荐年龄')
    qiniu_pic = models.CharField(max_length=100, blank=True, null=True, verbose_name='七牛配图')
    douban_star = models.CharField(max_length=20, blank=True, null=True, verbose_name='豆瓣星数')
    douban_rank = models.DecimalField(max_digits=2, decimal_places=1, verbose_name='豆瓣评级')
    douban_cnt_voted = models.CharField(max_length=20, blank=True, null=True, verbose_name='豆瓣评价人数')
    isbn = models.CharField(max_length=20, blank=True, null=True, verbose_name='ISBN书号')
    cover = models.CharField(max_length=10, blank=True, null=True, verbose_name='装帧')
    active = models.BooleanField(default=False, verbose_name='有效')
    expired = models.BooleanField(default=False, verbose_name='过期')
    create_at = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
    modify_at = models.DateTimeField(blank=True,null=True,verbose_name='修改时间')

    def save(self, *args, **kwargs):
        self.modify_at = datetime.datetime.today()
        if self.data_from == '1' and self.sku and not self.active:
            # self.article_title_pinyin = pinyin.get_initials(self.article_title, '')
            fetch_book_info_by_sku.delay(self)
        if self.date_from == '2' and self.isbn and not self.active:
            fetch_book_info_from_douban.delay(self)
        return super(Book, self).save(*args, **kwargs)

    class Meta:
        verbose_name = '图书目录'
        verbose_name_plural = '图书目录'
        ordering = ('-create_at',)

    def __str__(self):
        # return str(self.article_title)
        return (self.name[:25] + '..') if len(self.name) > 25 else self.name

    '''
    def as_json(self):
        return dict(
            id = self.id,
            sku = self.sku,
            name = self.name,
            top_category = self.top_category,
            sub_category = self.sub_category,
            pic = self.pic,
            url = self.url,
            url_refer = self.url_refer,
            create_at = self.create_at.strftime('%Y-%m-%d %H:%M:%S') if self.create_at else None,
            modify_at = self.modify_at.strftime('%Y-%m-%d %H:%M:%S') if self.modify_at else None,
        )
    '''

    @staticmethod
    def query_top_items_by(keyword, len):
        date_before_30_days = get_date_by_delta(datetime.datetime.today(), -30)
        return Book.objects.filter(create_at__gte=date_before_30_days, article_title__icontains=keyword, active=True).order_by('-modify_at').order_by('-create_at')[:len]

